package com.demo.controller;

import com.demo.entity.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

//用户登录与注册操作
@Controller // 加入IOC容器
@RequestMapping("controller")
public class UserController {
	// 控制器依赖于Service
	@Autowired
	@Qualifier("userService")
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	// 登录
	@RequestMapping("loginAction")
	public String compLoginAction(HttpServletRequest request, User user, Map<String, Object> map) {
		String loginname = (String) request.getSession().getAttribute("USERNAME");
		// 获取表单数据：User属性 必须 和 form表单中的属性Name值一致（支持级联属性）
		String uname = user.getUsername();
		String upwd = user.getPassword();
		User userDB;

		if(uname==null || upwd==null){
			request.setAttribute("messageLog", "非法操作，请注意 ! ");
			return "forward:/login.jsp";
		}

		if (uname.indexOf("@") == -1) { // 账号+密码登录
			userDB = userService.queryUserLogin(uname, upwd);
		} else { // 邮箱+密码登录
			userDB = userService.queryUserLoginByEmail(uname);
		}

		// userDB.getType()获取登录者的身份
		if (userDB != null && userDB.getType() == 0) {
			if (uname.equals(loginname)) {
				request.getSession().invalidate(); 		// 销毁session
			}
			request.getSession().setAttribute("USERNAME", userDB.getUsername());
			map.put("userdb", userDB);
			return "pageUser"; // views/pageUser.jsp，默认使用请求转发的方式跳转-用户界面
		} else if (userDB != null && userDB.getType() == 1) {
			if(uname.equals(loginname)){
				request.getSession().invalidate(); 			//销毁session
			}
			request.getSession().setAttribute("USERNAME", userDB.getUsername());
			map.put("userdb", userDB);
			return "pageAdmin"; // views/pageAdmin.jsp，默认使用请求转发的方式跳转-管理员界面
		} else {
			String message = "账号或密码有误 ! ";
			request.setAttribute("messageLog", message);
			return "forward:/login.jsp"; // 指定跳转方式：重定向
		}
		// return "redirect:/login.jsp";
	}

	// 注册
	@RequestMapping("registerAction")
	public String compRegisterAction(HttpServletRequest request, User user, Map<String, Object> map) throws UnsupportedEncodingException {

		// 获取表单数据：User属性 必须 和 form表单中的属性Name值一致（支持级联属性）
		String email = user.getEmail();
		String uname = new String(user.getUsername().getBytes("iso-8859-1"),"UTF-8");
		String upwd = user.getPassword();

		if(email==null || uname==null || upwd==null){
			request.setAttribute("messageRe", "非法操作，请注意 ! ");
			return "forward:/register.jsp";
		}
		//1.改数据-表-用户名唯一约束		或  	2.先查询判断再做操作
		try{
			userService.insertUserRegister(email, uname, upwd);
			request.setAttribute("messageRe", "注册成功!");
		} catch(Exception e){
			request.setAttribute("messageRe", "账号已被占用，请更换账号重新注册 ! ");
			System.out.println("注册用户名已被占用\n"+e.getMessage());
		} finally{
			return "forward:/register.jsp"; 			// 指定跳转方式：重定向
		}

	}

	// 查询所有用户信息
	@RequestMapping("user_info_list_action")
	public String queryUserInformation(HttpServletRequest request) {
		List<User> userInfo = userService.queryUserInfo();
		request.getSession().setAttribute("userInfoList", userInfo);
		return "user_info_list";
	}

	// 删除用户信息
	@RequestMapping("user_info_del_action/{delID}")
	public String delUserInformation(@PathVariable("delID") String delID) {
		userService.delUserInfo(delID);
		System.out.println("删除用户：" + delID + "成功");
		return "redirect:/controller/user_info_list_action"; // 重定向到查询页-刷新
	}

	// 查看单个用户的信息
	@RequestMapping("showUserInfo/{uid}")
	public String showOneUserInfo(@PathVariable("uid") String uid, HttpServletRequest req) {
		List<User> userList = (List<User>) req.getSession().getAttribute("userInfoList");
		User user = new User();
		for (User userInfoList : userList) {
			if (userInfoList.getUserId() == Integer.parseInt(uid)) {
				user.setUserId(userInfoList.getUserId());
				user.setUsername(userInfoList.getUsername());
				user.setType(userInfoList.getType());
				user.setState(userInfoList.getState());
				user.setEmail(userInfoList.getEmail());
				user.setPassword(userInfoList.getPassword());
				user.setRegistTime(userInfoList.getRegistTime());
			}
		}
		req.getSession().setAttribute("user", user);
		return "updateUser";
	}

	// 修改用户权限
	@RequestMapping("user_info_update_action/{uid}")
	public String updateUserInfo(@PathVariable("uid") String uid, HttpServletRequest req) {
		User userinfo = (User) req.getSession().getAttribute("user");
		int userState = userinfo.getState();
		int userType = userinfo.getType();

		int guState = Integer.parseInt(req.getParameter("userState"));
		int guType = Integer.parseInt(req.getParameter("userType"));
		System.out.println(userState + "-" + userType + "\t" + guState + "-" + guType);
		if (userState != guState) {
			userState = guState;
		}
		if (userType != guType) {
			userType = guType;
		}

		userService.updateUserPower(uid, userState, userType);
		System.out.println("修改用户权限cg........................");
		req.getSession().setAttribute("updateUserMessage", "用户权限修改成功 ! ");
		return "updateUser";
	}

}

}
